package berlinatyourfingertips.ua.apis;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import berlinatyourfingertips.ua.UAInterface;
import berlinatyourfingertips.ua.UAResult;
import berlinatyourfingertips.ua.UAResultSet;

/**
 * Unified panoramio requester
 * 
 * @author Denny Koch
 *
 */
public class UAPanoramio implements UAInterface {
	
	private String size, set, order;
	private float areaSize;
	
	/**
	 * .2f, "upload_date", "full", "thumbnail"
	 * @param areaSize
	 * @param order
	 * @param set
	 * @param size
	 */
	public UAPanoramio(float areaSize, String order, String set, String size) {
		this.areaSize	=	areaSize;
		this.size		=	size;
		this.set		=	set;
		this.order		=	order;
	}
	
	private UAResultSet request(float latitude, float longitude) {
		System.out.println("Panoramio: request startet.");
		
		UAResultSet result = new UAResultSet();
		
		String httpResult = UAHttp.get("http://www.panoramio.com/map/get_panoramas.php?order="+order+"&set="+set+"&from=0&to=100&minx="+(latitude-(areaSize/2))+"&miny="+(longitude-(areaSize/2))+"&maxx="+(latitude+(areaSize/2))+"&maxy="+(longitude+(areaSize/2))+"&size="+size);
		
		// System.out.println(httpResult);
		
		try {
			System.out.println("Panoramio: processing result.");
			
			JSONObject jos = new JSONObject(new JSONTokener(httpResult));
			JSONArray  ja = jos.getJSONArray("photos");
			for(int i = 0; i < ja.length(); i++) {
				float lati = (float)ja.getJSONObject(i).getDouble("latitude");
				float longi = (float)ja.getJSONObject(i).getDouble("longitude");
				System.out.println("Panoramio: adding "+lati+"/"+longi);
				result.add(new UAResult(lati, longi));
			}
		} catch (JSONException e) {
			System.err.println("Panoramio: json parsing error.");			
			e.printStackTrace();
		}
		
		return result;
	}
	
	public UAResultSet getAllAtPosition(float latitude, float longitude) {
		return request(latitude, longitude);
	}

	public UAResultSet getPosition(int maxResultLength, float latitude, float longitude) {
		return getAllAtPosition(latitude, longitude);
	}

	/**
	 * Disabled!!! Will always return an empty result
	 */
	public UAResultSet getAll() {
		return new UAResultSet();
	}

}
